<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="utf-8">
	<title>添加</title>
	<meta name="renderer" content="webkit">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="viewport"
		content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
	<link rel="stylesheet" href="/layui/css/layui.css">
</head>

<body>
	<div style="padding: 20px;">
		<form class="layui-form layui-form-pane" action="" lay-filter="addForm">
			<div class=" layui-card-body  gridAuto">
				<div class="layui-form-item">
					<label class="layui-form-label">用户名</label>
					<div class="layui-input-block">
						<input type="text" name="username" lay-verify="required" autocomplete="off" placeholder="请输入用户名"
							class="layui-input">
					</div>
				</div>

				<div class="layui-form-item">
					<label class="layui-form-label">真实姓名</label>
					<div class="layui-input-block">
						<input type="text" name="truename" lay-verify="required" autocomplete="off"
							placeholder="请输入真实姓名" class="layui-input">
					</div>
				</div>

				<div class="layui-form-item">
					<label class="layui-form-label">所属部门</label>
					<div class="layui-input-block">
						<input type="hidden" name="deptid" id="deptId">
						<div id="deptTree" style="width: 100%"></div>
					</div>
				</div>

				<div class="layui-form-item">
					<label class="layui-form-label">用户角色</label>
					<div class="layui-input-block">
						<input type="hidden" name="roleids" id="roleIds">
						<div id="roleTree" style="width: 100%"></div>
					</div>
				</div>

				<div class="layui-form-item">
					<label class="layui-form-label">联系电话</label>
					<div class="layui-input-block">
						<input type="text" name="phone" lay-verify="phone" autocomplete="off" placeholder="请输入电话"
							class="layui-input">
					</div>
				</div>

				<div class="layui-form-item">
					<label class="layui-form-label">电子邮箱</label>
					<div class="layui-input-block">
						<input type="email" name="emaile" lay-verify="email" autocomplete="off" placeholder="请输入邮箱"
							class="layui-input">
					</div>
				</div>

				<div class="layui-form-item">
					<label class="layui-form-label">监管级别</label>
					<div class="layui-input-block">
						<select name="jgjb" lay-verify="required" lay-search>
							<option value="">请选择监管级别</option>
							<!-- 动态加载选项 -->
						</select>
					</div>
				</div>

				<div class="layui-form-item">
					<label class="layui-form-label">用户类型</label>
					<div class="layui-input-block">
						<select name="user_type" lay-verify="required" lay-search>
							<option value="">请选择用户类型</option>
							<!-- 动态加载选项 -->
						</select>
					</div>
				</div>

				<div class="layui-form-item">
					<label class="layui-form-label">账号状态</label>
					<div class="layui-input-block">
						<input type="checkbox" name="isenabled" lay-skin="switch" lay-filter="switchTest" title="启用|禁用">
					</div>
				</div>

				<div class="layui-form-item layui-form-text">
					<label class="layui-form-label">备注说明</label>
					<div class="layui-input-block">
						<textarea name="remark" placeholder="请输入备注" class="layui-textarea"></textarea>
					</div>
				</div>

				<div class="layui-form-item" style="text-align: center; margin-top: 30px;">
					<input type="hidden" name="id">
					<button type="submit" class="layui-btn layui-btn-normal" lay-submit
						lay-filter="YjbtnSave">立即提交</button>
					<button type="reset" class="layui-btn layui-btn-primary">重置</button>
				</div>
			</div>
		</form>
	</div>
	<script src="/layui/layui.js"></script>
	<script src="/src/lib/extend/xm-select.js"></script>
	<script>
		layui.use(function () {
			var form = layui.form
				, admin = parent.layui.admin
				, table = parent.layui.table
			$ = layui.$;


			//动态加载监管级别和用户类型选项
			function loadJgjbOptions(type) {
				return new Promise((resolve) => {
					admin.req({
						url: 'sysDict/getDictList',
						data: {
							dtype: type === 0 ? "UserJGJB" : "UserType",
							page: 1,
							status: 0,
							limit: 1000
						},
						done: function (res) {
							if (res.successful) {
								var $select = type === 0
									? $('select[name="jgjb"]')
									: $('select[name="user_type"]');

								// 清空并添加选项
								$select.empty().append('<option value="">请选择</option>');
								res.data.data.forEach(function (item) {
									$select.append(
										`<option value="${item.dvalue}">${item.dname}</option>`
									);
								});

								// 渲染下拉框
								form.render('select');
								resolve();
							}
						}
					});
				});
			}
			// 初始化部门树
			var deptTree = null;
			function initDeptTree(selectedId) {
				admin.req({
					url: 'sysdept/getdeptlist',
					data: { page: 1, limit: 10000 },
					done: function (res) {
						if (res.successful) {
							// 将扁平数据转换为树形结构s
							const deptData = res.data.data;
							const treeData = buildTree(deptData, selectedId, 0);

							// 获取需要展开的路径
							const expandedKeys = selectedId
								? findDeptPath(selectedId, deptData).slice(0, -1).map(String) // 去掉最后一个元素
								: [];

							// 初始化树形选择器
							deptTree = xmSelect.render({
								el: '#deptTree',
								model: { label: { type: 'text' } },
								radio: true,
								clickClose: true,
								filterable: true,
								layVerify: 'required',
								tree: {
									show: true,
									strict: false,
									expandedKeys: expandedKeys // 设置展开路径,
								},
								data: treeData,
								on: function (data) {
								}
							});

							// 设置选中值（需在展开后执行）
							setTimeout(() => {
								if (selectedId) {
									deptTree.setValue([selectedId.toString()]);
								}
							}, 100);
						}
					}
				});
			}
			// 初始化角色树
			var roleTree = null;
			function initRoelTree(selectedroleId) {
				admin.req({
					url: 'sysrole/getrolelist',
					data: { page: 1, limit: 10000 },
					done: function (res) {
						if (res.successful) {
							// 将扁平数据转换为树形结构s

							const roleData = res.data.data;
							const treeData = buildTree(roleData, selectedroleId, 1);



							// 将字符串转换为数组
							const selectedIds = selectedroleId
								? selectedroleId.split(',').map(String)
								: [];



							// 获取所有选中节点的展开路径
							let expandedKeys = [];
							selectedIds.forEach(id => {
								const path = findDeptPath(id, roleData);
								expandedKeys.push(...path.slice(0, -1).map(String));
							});
							expandedKeys = [...new Set(expandedKeys)]; // 去重


							// 初始化树形选择器
							roleTree = xmSelect.render({
								el: '#roleTree',
								model: { label: { type: 'text' } },
								clickClose: false,
								filterable: true,
								tree: {
									show: true,
									strict: false,
									expandedKeys: expandedKeys // 设置展开路径,
								},
								data: treeData,
							});

							// 设置选中值（需在展开后执行）
							setTimeout(() => {
								if (selectedroleId) {
									roleTree.setValue(selectedIds);
								}
							}, 100);
						}
					}
				});
			}
			function buildTree(data, selectedId, type) {
				const map = {};
				const tree = [];

				// 创建映射表
				data.forEach(item => {
					if (type == 0) {

						map[item.id] = {
							...item,
							value: item.id.toString(), // 必须转换为字符串
							name: item.name,
							children: [],
							// 非编辑模式下，已禁用的部门角色禁止操作
							// 复合禁用条件：status=1 或 有子节点 且 不是当前选中节点，部门的不在判断是否有子节点
							disabled: item.status === 1 && item.id != selectedId
						};
					}
					else {
						// 将字符串转换为数组
						const selectedIds = selectedId
							? selectedId.split(',').map(String)
							: [];

						const isSelected = selectedIds.includes(String(item.id)); // 是否选中

						map[item.id] = {
							...item,
							value: item.id.toString(), // 必须转换为字符串
							name: item.name,
							children: [],
							// 非编辑模式下，已禁用的部门角色禁止操作
							// 复合禁用条件：status=1 或 有子节点 且 不是当前选中节点，部门的不在判断是否有子节点
							disabled: (item.status === 1 || item.haschildren) && !isSelected
						};
					}
				});

				// 构建树形结构
				data.forEach(item => {
					const parent = map[item.pid];
					if (parent) {
						parent.children.push(map[item.id]);
					} else {
						tree.push(map[item.id]);
					}
				});

				return tree;
			}

			// 在部门数据中查找父级路径
			function findDeptPath(deptId, deptData) {
				const path = [];
				let currentId = deptId;

				while (currentId !== undefined && currentId !== 0) {
					const dept = deptData.find(d => d.id == currentId);
					if (!dept) break;
					path.unshift(dept.id); // 向前插入形成正序路径
					currentId = dept.pid;
				}

				return path;
			}

			// 初始化表单数据
			function initForm() {
				var id = getQueryParam('id');
				if (id) { // 编辑模式
					// 先加载下拉框选项
					Promise.all([
						loadJgjbOptions(0), // 监管级别
						loadJgjbOptions(1)  // 用户类型
					]).then(() => {
						admin.req({
							url: 'sysUser/GetUserInfoByID/' + id,
							done: function (res) {
								if (res.successful) {
									var status = res.data.isenabled === 0;
									res.data.isenabled = status;
									// 填充基础字段
									form.val('addForm', res.data);

									// 初始化部门树并设置选中
									initDeptTree(res.data.deptid);
									//初始化角色树并设置选中
									initRoelTree(res.data.roleids);
								}
								else {
									admin.msg_error(res.msg);

								}
							}
						});
					});
				} else {
					// 新增模式
					loadJgjbOptions(0);// 监管级别
					loadJgjbOptions(1);  // 用户类型
					initDeptTree();
					initRoelTree();
				}
			}

			// 初始化执行
			initForm();



			//添加
			form.render().on('submit(YjbtnSave)', function (data) {

				// 获取选中的部门
				var checkDept = deptTree.getValue()[0];
				var checkRole = roleTree.getValue();
				var roleIds = checkRole.map(item => item.id).join(',');
				data.field.roleids = roleIds;
				data.field.deptid = checkDept.id;
				data.field.areanumber = checkDept.areacode;
				data.field.isenabled = data.field.isenabled ? 0 : 1;
				admin.req({
					url: data.field.id ? 'sysUser/updateUser' : 'sysUser/addUser'
					, data: JSON.stringify(data.field)
					, contentType: 'application/json'
					, async: true
					, type: data.field.id ? 'PUT' : 'POST'
					, done: function (res) {
						if (res.successful) {							
							table.reload('LAY-app-user-list');
							parent.layer.closeAll();
							admin.msg_success(data.field.id ? '修改成功！' : '添加成功！');
						}
						else {
							admin.msg_error(res.msg);
							return false;
						}
					}
				});
			})

			// 获取URL参数方法
			function getQueryParam(name) {
				const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
				const r = window.location.search.substr(1).match(reg);
				return r ? decodeURIComponent(r[2]) : null;
			}
		});
	</script>
</body>

</html>